<?php
/**
 * Created by PhpStorm.
 * User: dell
 * Date: 2019/5/22
 * Time: 17:32
 */
namespace Modules\Admin\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Lib\upload;
use App\Models\Goods;
use App\Models\GoodsClass;
use App\Models\GoodsColor;
use App\Models\GoodsSku;
use App\Models\Order;
use App\Models\OrderEvaluate;
use App\Models\OrderGoods;
use App\Models\System;
use App\Models\Wechart;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class GoodsController extends Controller{
    //类型列表
    public function goodsClassListApi(Request $request){
        try{
            $page = $request->input("page",1);
            $size = $request->input("limit",20);
            $count = GoodsClass::count();
            $data = GoodsClass::forPage($page,$size)->orderBy('id','desc')->get();
            return self::jsondata($count,$data);
        }catch (\Exception $e){
            Log::error($e);
            return self::error(500);
        }
    }

    //新增商品类型
    public function goodsClassAddApi(Request $request){
        try{
            $className = $request->input("class_name",false);
            if (!$className)return self::error(1000);
            $class = new GoodsClass();
            $class->class_name = $className;
            $class->created_at = Carbon::now();
            $class->save();
            return self::success();
        }catch (\Exception $e){
            Log::error($e);
            return self::error(500);
        }
    }

    //编辑商品类型
    public function goodsClassEditApi(Request $request){
        try{
            $id = $request->input("id");
            $className = $request->input("class_name");
            $goodsclass = GoodsClass::find($id);
            $goodsclass->class_name = $className;
            $goodsclass->save();
            return self::success();
        }catch (\Exception $e){
            Log::error($e);
            return self::error(500);
        }
    }

    //删除商品类型
    public function goodsClassDeleteApi(Request $request){
        try{
            $id = $request->input("id",false);
            if (!$id)return self::error(1000);
            $goodsClass = GoodsClass::find($id);
            $goodsClass->delete();
            return self::success();

        }catch (\Exception $e){
            Log::error($e);
            return self::error(500);
        }
    }

    //上传文件
    public function upload(){
        try{
            $data = upload::uploadOne('files');
            return self::success(["image"=>$data['data']]);
        }catch (\Exception $e){
            Log::error($e);
            return self::error(500);
        }
    }

    //上传商品
    public function goodsAddApi(Request $request){
        try{
            $goodsName = $request->input("goods_name",false);
            $price = $request->input("price",false);
            $classId = $request->input("class_id",false);
            $freeShopping = $request->input("is_free_shopping",1);
            $image = $request->input("image",false);
            $detail = $request->input("detail");
            $sku = $request->input("sku",false);
            $color = $request->input("color",false);
            if (!$goodsName || !$classId || !$price || !$image || !$sku || !$color)return self::error(1000);
            $goodsClass = GoodsClass::find($classId);
            if (!$goodsClass)return self::error(1003);

            //查询兑换比例
            $sys = System::find(1);
            if ($sys){
                $duiHuan = $sys->score_ratio;
            }else{
                $duiHuan = 2.5;
            }

            DB::beginTransaction();

            $goods = new Goods();
            $goods->goods_name = $goodsName;
            $goods->class_id = $goodsClass->id;
            $goods->class_name = $goodsClass->class_name;
            $goods->image = $image;
            $goods->detail = $detail;
            $goods->price = $price;
            $goods->integral = $price*$duiHuan;
            $goods->is_free_shopping = $freeShopping;
            $goods->status = 1;
            $goods->created_at = Carbon::now();
            $goods->save();

            //切割规格
            $skuA = explode(',',$sku);
            foreach ($skuA as $item){
                $skuB = explode('|&|',$item);
                $goodsSku = new GoodsSku();
                $goodsSku->goods_id = $goods->id;
                $goodsSku->sku_name = $skuB[0];
                $goodsSku->sku_price = $skuB[1];
                $goodsSku->sku_score = $skuB[1]*$duiHuan;
                $goodsSku->created_at = Carbon::now();
                $goodsSku->save();
            }
            //切割颜色
            $colorA = explode(',',$color);
            foreach ($colorA as $item){
                $colorB = explode('|&|',$item);
                $goodsColor = new GoodsColor();
                $goodsColor->goods_id = $goods->id;
                $goodsColor->color_name = $colorB[0];
                $goodsColor->color_image = $colorB[1];
                $goodsColor->created_at = Carbon::now();
                $goodsColor->save();
            }

            DB::commit();
            return self::success();
        }catch (\Exception $e){
            Log::error($e);
            DB::rollback();
            return self::error(500);
        }
    }

    //商品编辑
    public function goodsEditApi(Request $request){
        try{
            $id = $request->input("id");
            $classId = $request->input("class_id");
            $goodsName = $request->input("goods_name",false);
            $price = $request->input("price",false);
            $image = $request->input("image",false);
            $detail = $request->input("detail");
            $freeShopping = $request->input("is_free_shopping",false);
            if (!$goodsName || !$classId || !$price || !$image || !$id)return self::error(1000);
            $goodsClass = GoodsClass::find($classId);
            //查询兑换比例
            $sys = System::find(1);
            if ($sys){
                $duiHuan = $sys->score_ratio;
            }else{
                $duiHuan = 2.5;
            }
            if (!$goodsClass)return self::error(1003);
            $goods = Goods::find($id);
            $goods->class_id = $classId;
            $goods->class_name = $goodsClass->class_name;
            $goods->goods_name = $goodsName;
            $goods->image = $image;
            $goods->detail = $detail;
            $goods->price = $price;
            $goods->integral = $price*$duiHuan;
            $goods->is_free_shopping = $freeShopping;
            $goods->save();
            return self::success();
        }catch (\Exception $e){
            Log::error($e);
            return self::error(500);
        }
    }

    //商品列表
    public function goodsListApi(Request $request){
        try{
            $page = $request->input("page",1);
            $limit = $request->input("limit",20);
            $id = $request->input("id",false);
            $goods_name = $request->input("goods_name",false);
            $query = Goods::query();
            if ($id){
                $query->where("id",$id);
            }
            if ($goods_name){
                $query->where("goods_name","like","%{$goods_name}%");
            }
            $count = $query->count();
            $data = $query->skip(($page-1)*$limit)->take($limit)->orderBy('id','desc')->get();
            $goods = [];
            if ($count>0){
                foreach ($data as $item){
                    $skuData = GoodsSku::where("goods_id",$item['id'])->select('id','sku_name')->get();
                    $colorData = GoodsColor::where("goods_id",$item['id'])->select('id','color_name')->get();
                    $item['sku'] = $skuData;
                    $item['color'] = $colorData;
                    $goods[] = $item;
                }
            }
            return self::jsondata($count,$goods);
        }catch (\Exception $e){
            Log::error($e);
            return self::error(500);
        }
    }

    //删除商品
    public function goodsDeleteApi(Request $request){
        try{
            $id = $request->input("id",false);
            if (!$id)return self::error(1000);
            DB::beginTransaction();
            $goods = Goods::find($id);
            $goods->delete();
            $sku = GoodsSku::where("goods_id",$id)->delete();
            $color = GoodsColor::where("goods_id",$id)->delete();
            DB::commit();
            return self::success();
        }catch (\Exception $e){
            Log::error($e);
            DB::rollBack();
            return self::error(500);
        }
    }

    //查询规格
    public function goodsSkuListApi(Request $request){
        try{
            $id = $request->input("id",false);
            if(!$id)return self::error(1000);
            $sku = GoodsSku::where("goods_id",$id)->get();
            return self::jsondata(0,$sku);
        }catch (\Exception $e){
            Log::error($e);
            return self::error(500);
        }
    }


    //查询颜色
    public function goodsColorListApi(Request $request){
        try{
            $id = $request->input("id",false);
            if(!$id)return self::error(1000);
            $color = GoodsColor::where("goods_id",$id)->get();
            return self::jsondata(0,$color);
        }catch (\Exception $e){
            Log::error($e);
            return self::error(500);
        }
    }

    //上传规格
    public function goodsSkuAddApi(Request $request){
        try{
            $goodsId = $request->input("goods_id",false);
            $skuName = $request->input("sku_name",false);
            $skuPrice = $request->input("sku_price",false);
            if (!$goodsId || !$skuName || !$skuPrice)return self::error(1000);
            $goods = Goods::find($goodsId);
            if (!$goods)return self::error(1005);
            $skuData = GoodsSku::where("goods_id",$goodsId)->where("sku_name",$skuName)->first();
            //查询兑换比例
            $sys = System::find(1);
            if ($sys){
                $duiHuan = $sys->score_ratio;
            }else{
                $duiHuan = 2.5;
            }
            if ($skuData)return self::error(1011);
            $sku = new GoodsSku();
            $sku->goods_id = $goodsId;
            $sku->sku_name = $skuName;
            $sku->sku_price = $skuPrice;
            $sku->sku_score = $skuPrice*$duiHuan;
            $sku->created_at = Carbon::now();
            $sku->save();

            return self::success();
        }catch (\Exception $e){
            Log::error($e);
            return self::error(500);
        }
    }

    //上传颜色
    public function goodsColorAddApi(Request $request){
        try{
            $goodsId = $request->input("goods_id",false);
            $colorName = $request->input("color_name",false);
            if (!$goodsId || !$colorName)return self::error(1000);
            $goods = Goods::find($goodsId);
            if (!$goods)return self::error(1005);
            $goodsColor = GoodsColor::where("goods_id",$goodsId)->where('color_name',$colorName)->first();
            if ($goodsColor)return self::error(1011);
            $file = upload::uploadOne('files');

            $color = new GoodsColor();
            $color->goods_id = $goodsId;
            $color->color_name = $colorName;
            $color->color_image = $file['data'];
            $color->created_at = Carbon::now();
            $color->save();

            return self::success();
        }catch (\Exception $e){
            Log::error($e);
            return self::error(500);
        }
    }

    //删除商品图
    public function goodsImageDeleteApi(Request $request){
        try{
            $id = $request->input("id",false);
            $type = $request->input("type",false);
            $image = $request->input("image",false);
            if (!$type || !$image || !$id)return self::error(1000);
            $goods = Goods::find($id);
            $image = str_replace(Wechart::PATH_IMAGE.'uploads/',"",$image);
            if ($type==1){
                //切割数组
                $exp = explode(',',$goods->image_text);
                $str = '';
                foreach ($exp as $item){
                    if ($item!=$image){
                        $str = $str.','.$item;
                    }
                }
                $strImage = ltrim($str,',');
                $goods->image = $strImage;
                $goods->save();
            }else{
                //切割数组
                $exp = explode(',',$goods->detail_text);
                $str = '';
                foreach ($exp as $item){
                    if ($item!=$image){
                        $str = $str.','.$item;
                    }
                }
                $strImage = ltrim($str,',');
                $goods->detail = $strImage;
                $goods->save();
            }
            return self::success();
        }catch (\Exception $e){
            Log::error($e);
            return self::error(500);
        }
    }

    //删除规格
    public function goodsSkuDeleteApi(Request $request){
        try{
            $id = $request->input("id",false);
            if (!$id)return self::error(1000);
            $sku = GoodsSku::find($id);
            $sku->delete();
            return self::success();
        }catch (\Exception $e){
            Log::error($e);
            return self::error(500);
        }
    }

    //删除颜色
    public function goodsColorDeleteApi(Request $request){
        try{
            $id = $request->input("id",false);
            if (!$id)return self::error(1000);
            $color = GoodsColor::find($id);
            $color->delete();
            return self::success();
        }catch (\Exception $e){
            Log::error($e);
            return self::error(500);
        }
    }

    //查询商品规格销量
//    public function goodsSkuDataApi(Request $request){
//        try{
//            $goodsId = $request->input("goods_id",false);
//            if (!$goodsId)return self::error(1000);
//            $goodsSku = GoodsSku::where("goods_id",$goodsId)->orderBy("sell_num","desc")->get();
//            return self::success($goodsSku);
//        }catch (\Exception $e){
//            Log::error($e);
//            return self::error(500);
//        }
//    }

    //查询商品规格销量
//    public function goodsColorDataApi(Request $request){
//        try{
//            $goodsId = $request->input("goods_id",false);
//            if (!$goodsId)return self::error(1000);
//            $goodsColor = GoodsColor::where("goods_id",$goodsId)->orderBy("sell_num","desc")->get();
//            return self::success($goodsColor);
//        }catch (\Exception $e){
//            Log::error($e);
//            return self::error(500);
//        }
//    }

    //商品规格和颜色销量
    public function goodsSellSkuAndColorApi(Request $request){
        try{
            $goodsId = $request->input("goods_id",false);
            $startDate = $request->input("start_date",false);
            $endDate = $request->input("end_date",false);
            if (!$goodsId)return self::error(1000);
            $query = OrderGoods::query();
            if ($goodsId){
                $query->where("goods_id",$goodsId);
            }
            if ($startDate){
                $query->whereDate("created_at",">=",$startDate);
            }
            if ($endDate){
                $query->whereDate("created_at","<=",$endDate);
            }
            $ordersku = $query->with('order')->get();
            $goodssku = GoodsSku::where("goods_id",$goodsId)->get();
            $skuArray = [];
            if ($goodssku->count()>0){
                foreach ($goodssku as $item){
                    $sellNum = 0;
                    if ($ordersku->count()>0) {
                        foreach ($ordersku as $value) {
                            if ($item['id']==$value['sku_id']){
                                $sellNum+=$value['goods_num'];
                            }
                        }
                    }
                    $skuArray[] = ["sku_name"=>$item['sku_name'],"sell_num"=>$sellNum];
                }
            }
            $goodscolor = GoodsColor::where("goods_id",$goodsId)->get();
            $colorArray = [];
            if ($goodscolor->count()>0){
                foreach ($goodscolor as $item){
                    $sellNum = 0;
                    if ($ordersku->count()>0) {
                        foreach ($ordersku as $value) {
                            if ($item['id']==$value['color_id']){
                                $sellNum+=$value['goods_num'];
                            }
                        }
                    }
                    $colorArray[] = ["color_name"=>$item['color_name'],"sell_num"=>$sellNum];
                }
            }
            return self::success(["sku"=>$skuArray,"color"=>$colorArray]);
        }catch (\Exception $e){
            Log::error($e);
            return self::error(500);
        }
    }

    //查询商品评价
    public function goodsPingJiaDataApi(Request $request){
        try{
            $id = $request->input("id",false);
            if (!$id)return self::error(1000);
            $goods = Goods::find($id);
            $count = OrderEvaluate::where("goods_id",$goods->id)->count();
            $ping = OrderEvaluate::where("goods_id",$goods->id)->with('user')->orderBy('id','desc')->get();
            return self::jsondata($count,$ping);
        }catch (\Exception $e){
            Log::error($e);
            return self::error(500);
        }
    }

    //删除评价
    public function goodsPingJiaDeleteApi(Request $request){
        try{
            $id = $request->input("id",false);
            if (!$id)return self::error(1000);
            $ping = OrderEvaluate::find($id);
            $ping->delete();
            return self::success();
        }catch (\Exception $e){
            Log::error($e);
            return self::error(500);
        }
    }

    //添加评价
    public function goodsPingJiaAddApi(Request $request){
        try{
            $userId = $request->input("userid",false);
            $content = $request->input("content",false);
            $image = $request->input("image",false);
            $goodsId = $request->input("goods_id",false);
            if (!$userId || !$content || !$goodsId)return self::error(1000);
            //随机生成订单号
            $orderSn = 'DZ'.date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 6);
            $ping = new OrderEvaluate();
            $ping->userid = $userId;
            $ping->order_id = 0;
            $ping->order_sn = $orderSn;
            $ping->goods_id = $goodsId;
            $ping->content = $content;
            $ping->image = $image;
            $ping->star = 5;
            $ping->created_at = Carbon::now();
            $ping->save();
            return self::success();
        }catch (\Exception $e){
            Log::error($e);
            return self::error(500);
        }
    }
}